package com.enation.app.web.core.action.backend;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.enation.app.base.core.model.PluginDataMapper;
import com.enation.app.web.core.model.Address;
import com.enation.app.web.core.model.Member;
import com.enation.app.web.core.plugin.member.MemberPluginBundle;
import com.enation.app.web.core.service.IAddressManager;
import com.enation.app.web.core.service.IMemberManager;
import com.enation.framework.action.GridController;
import com.enation.framework.action.GridJsonResult;
import com.enation.framework.action.JsonResult;
import com.enation.framework.image.IUploader;
import com.enation.framework.util.DateUtil;
import com.enation.framework.util.FileUtil;
import com.enation.framework.util.JsonResultUtil;
import com.enation.framework.util.JsonUtil;
import com.enation.framework.util.StringUtil;
import com.enation.framework.util.UploadFacatory;

/**
 * 
 * @function 后台成员控制
 * @author 闯哥
 * @time 2016年12月3日 上午11:10:12
 */
@Controller
@RequestMapping("/core/admin/member")
public class MemberAdminController extends GridController {

	@Autowired
	private IMemberManager memberManager;

	@Autowired
	private IAddressManager addressManager;

	@Autowired
	private MemberPluginBundle memberPluginBundle;

	/**
	 * 
	 * @function 访问成员列表视图
	 * @return :成员列表视图
	 */
	@RequestMapping(value = "/list")
	public ModelAndView list() {
		ModelAndView view = new ModelAndView();
		List<Address> provinceList = this.addressManager.getProvince();
		if (provinceList.get(0).getId() == 0) {
			provinceList.remove(0);
		}
		view.addObject("provinceList", provinceList);
		view.setViewName("/core/admin/member/member_list");
		return view;
	}

	/**
	 * 
	 * @function 显示成员列表
	 * @return :成员集合
	 */
	@ResponseBody
	@RequestMapping(value = "/list-json")
	public GridJsonResult listJson(String student_number, String phone,
			String start_time, String end_time, String real_name,
			String nick_name, String grade, String sex, String province_id,
			String city_id, String region_id) {

		Map<String, String> result = new HashMap<String, String>();
		result.put("student_number", student_number);
		result.put("phone", phone);
		result.put("start_time", start_time);
		result.put("end_time", end_time);
		result.put("real_name", real_name);
		result.put("nick_name", nick_name);
		result.put("grade", grade);
		result.put("sex", sex);
		result.put("province_id", province_id);
		result.put("city_id", city_id);
		result.put("region_id", region_id);

		this.webpage = this.memberManager.findByPage(this.getPage(),
				this.getPageSize(), result);
		return JsonResultUtil.getGridJson(webpage);
	}

	/**
	 * 
	 * @function 增加成员页面
	 * @return :增加成员视图
	 */
	@RequestMapping(value = "/add-view")
	public ModelAndView addView() {
		ModelAndView view = new ModelAndView();

		List<Address> provinceList = this.addressManager.getProvince();
		if (provinceList.get(0).getId() == 0) {
			provinceList.remove(0);
		}
		view.addObject("provinceList", provinceList);

		view.setViewName("/core/admin/member/member_add");

		return view;
	}

	/**
	 * 
	 * @function 后台增加成员
	 * @param student_number
	 *            ----学号
	 * @param password
	 *            ----密码
	 * @param real_name
	 *            ----真实姓名
	 * @param nick_name
	 *            ----昵称
	 * @param sex
	 *            ----性别
	 * @return :消息
	 */
	@ResponseBody
	@RequestMapping(value = "/add")
	public JsonResult add(Member member, String strBirthday,
			@RequestParam(value = "pic", required = false) MultipartFile pic) {

		if (member.getStudent_number() == null) {
			return JsonResultUtil.getErrorJson("请求错误！学号没有填写！");
		}
		if (member.getStudent_number().equals("")) {
			return JsonResultUtil.getErrorJson("请求错误！学号没有填写！");
		}
		if (member.getPassword() == null) {
			return JsonResultUtil.getErrorJson("请求错误！密码没有填写！");
		}
		if (member.getPassword().equals("")) {
			return JsonResultUtil.getErrorJson("请求错误！密码没有填写！");
		}
		if (member.getReal_name() == null) {
			return JsonResultUtil.getErrorJson("请求错误！姓名没有填写！");
		}
		if (member.getReal_name().equals("")) {
			return JsonResultUtil.getErrorJson("请求错误！姓名没有填写！");
		}
		if (member.getNick_name() == null) {
			return JsonResultUtil.getErrorJson("请求错误！昵称没有填写！");
		}
		if (member.getNick_name().equals("")) {
			return JsonResultUtil.getErrorJson("请求错误！昵称没有填写！");
		}
		if (member.getSex() == null) {
			return JsonResultUtil.getErrorJson("请求错误！性别没有填写！");
		}
		if (member.getProvince_id() != 0) {
			if (member.getCity_id() == null || member.getRegion_id() == null
					|| member.getCity_id() == 0) {
				return JsonResultUtil.getErrorJson("请求错误！地址信息不完整！");
			}

			if (this.addressManager.checkexist(member.getProvince_id()) == 0) {
				return JsonResultUtil.getErrorJson("请求错误！");
			}
		}
		if (member.getCity_id() != null && member.getCity_id() != 0) {
			if (this.addressManager.checkexist(member.getCity_id()) == 0) {
				return JsonResultUtil.getErrorJson("请求错误！");
			}
		}
		if (member.getRegion_id() != null) {
			if (this.addressManager.checkexist(member.getRegion_id()) == 0) {
				return JsonResultUtil.getErrorJson("请求错误！");
			}
		}
		if (member.getPhone() != null) {
			String regExp = "^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$";
			Pattern p = Pattern.compile(regExp);
			Matcher m = p.matcher(member.getPhone());
			if (!m.matches()) {
				return JsonResultUtil.getErrorJson("请求错误！手机号码不正确！");
			}
		}
		if (member.getPw_question() == null || member.getPw_answer() == null) {
			member.setPw_question(null);
			member.setPw_answer(null);
		}

		// 学号验证
		String student_number = member.getStudent_number().toUpperCase();
		if (!student_number.startsWith("P1")) {
			return JsonResultUtil.getErrorJson("请求错误！学号填写错误！");
		}
		if (student_number.length() != 10) {
			return JsonResultUtil.getErrorJson("请求错误！学号填写错误！");
		}
		member.setStudent_number(student_number);

		// 判断密码是否符合规则
		if (member.getPassword().length() < 6
				|| member.getPassword().length() > 12) {
			return JsonResultUtil.getErrorJson("请求错误！密码填写不争取！");
		}

		// 查询是否注册过
		int flag = this.memberManager.checkIsRegister(student_number);
		if (flag == 1) {
			return JsonResultUtil.getErrorJson("该学号已经注册过了！");
		}

		// 查询昵称是否使用过
		flag = this.memberManager.checkNickName(member.getNick_name());
		if (flag == 1) {
			return JsonResultUtil.getErrorJson("该昵称已经注册过了！");
		}

		member.setPassword(StringUtil.md5(member.getPassword()));

		// 设置年级
		char one = student_number.charAt(1);
		char second = student_number.charAt(2);
		member.setGrade("20" + one + second + "级");

		// 上传图片
		if (pic != null) {
			if (FileUtil.isAllowUpImg(pic.getOriginalFilename())) {
				InputStream stream = null;
				try {
					stream = pic.getInputStream();
				} catch (Exception e) {
					e.printStackTrace();
				}
				IUploader uploader = UploadFacatory.getUploaer();
				String path = uploader.upload(stream, "adv",
						pic.getOriginalFilename());
				member.setPicture(path);
			} else {
				return JsonResultUtil
						.getErrorJson("不允许上传的文件格式，请上传gif,jpg,bmp,swf格式文件。");
			}
		} else {

			// 设置默认头像
			member.setPicture("fs:/images/default.gif");
		}

		// 设置生日
		if (strBirthday != null) {
			if (!strBirthday.equals("")) {
				try {
					Date date = DateUtil.toDate(strBirthday, "yyyy-MM-dd");
					member.setBirthday(date.getTime() / 1000);
				} catch (Exception e) {
					return JsonResultUtil.getErrorJson("请求错误！生日日期错误！");
				}
			}
		}

		member.setWeb_lvid(1);
		member.setPoint(0);
		member.setPublish(0);
		member.setSign_in(0);
		member.setIs_activation(1);

		Date date = new Date();
		member.setCreate_time(date.getTime() / 1000);

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");

		String ym = format.format(date);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(ym, "0");
		member.setLogincount(JsonUtil.MapToJson(map));

		try {
			this.memberManager.registor(member);

			return JsonResultUtil.getSuccessJson("注册成功！");

		} catch (Exception e) {
			e.printStackTrace();
			return JsonResultUtil.getErrorJson("注册失败！");
		}
	}

	/**
	 * 
	 * @function 删除成员
	 * @param member_ids
	 *            ----成员id数组
	 * @return :消息
	 */
	@ResponseBody
	@RequestMapping(value = "/delete")
	public JsonResult delete(Integer[] member_id) {

		String member_ids = "";
		for (int i = 0; i < member_id.length; i++) {
			if (i == member_id.length - 1) {
				member_ids = member_ids + member_id[i];
			} else {
				member_ids = member_ids + member_id[i] + ",";
			}

		}

		try {
			this.memberManager.delete(member_ids);

			return JsonResultUtil.getSuccessJson("删除成功！");
		} catch (Exception e) {
			return JsonResultUtil.getErrorJson("删除失败！");
		}
	}

	/**
	 * 
	 * @function 跳转修改会员页面
	 * @param memberId
	 *            ----会员id
	 * @return :视图
	 */
	@RequestMapping("/detail")
	public ModelAndView detail(Integer memberId) {

		ModelAndView view = new ModelAndView();
		List<PluginDataMapper> pluginDataMappers = this.memberPluginBundle
				.getDetailHtml(memberId);
		view.addObject("pluginTabs", pluginDataMappers);

		view.setViewName("/core/admin/member/member_edit");
		return view;
	}

	/**
	 * 
	 * @function 修改会员保存
	 * @param member
	 *            ----会员实体
	 * @param newpassword
	 *            ----新密码
	 * @return :消息
	 */
	@ResponseBody
	@RequestMapping("/edit-save")
	public JsonResult editSave(Member member, String newpassword,
			String strBirthday,
			@RequestParam(value = "pic", required = false) MultipartFile pic) {

		if (member.getMember_id() == null) {
			return JsonResultUtil.getErrorJson("请求错误！");
		}
		if (member.getMember_id().equals("")) {
			return JsonResultUtil.getErrorJson("请求错误！");
		}
		if (member.getStudent_number() == null) {
			return JsonResultUtil.getErrorJson("请求错误！学号没有填写！");
		}
		if (member.getStudent_number().equals("")) {
			return JsonResultUtil.getErrorJson("请求错误！学号没有填写！");
		}
		if (member.getReal_name() == null) {
			return JsonResultUtil.getErrorJson("请求错误！姓名没有填写！");
		}
		if (member.getReal_name().equals("")) {
			return JsonResultUtil.getErrorJson("请求错误！姓名没有填写！");
		}
		if (member.getNick_name() == null) {
			return JsonResultUtil.getErrorJson("请求错误！昵称没有填写！");
		}
		if (member.getNick_name().equals("")) {
			return JsonResultUtil.getErrorJson("请求错误！昵称没有填写！");
		}
		if (member.getSex() == null) {
			return JsonResultUtil.getErrorJson("请求错误！性别没有填写！");
		}
		if (member.getProvince_id() != 0) {
			if (member.getCity_id() == null || member.getRegion_id() == null
					|| member.getCity_id() == 0) {
				return JsonResultUtil.getErrorJson("请求错误！地址信息不完整！");
			}

			if (this.addressManager.checkexist(member.getProvince_id()) == 0) {
				return JsonResultUtil.getErrorJson("请求错误！");
			}
		}
		if (member.getCity_id() != null && member.getCity_id() != 0) {
			if (this.addressManager.checkexist(member.getCity_id()) == 0) {
				return JsonResultUtil.getErrorJson("请求错误！");
			}
		}
		if (member.getRegion_id() != null) {
			if (this.addressManager.checkexist(member.getRegion_id()) == 0) {
				return JsonResultUtil.getErrorJson("请求错误！");
			}
		}
		if (member.getPhone() != null) {
			String regExp = "^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$";
			Pattern p = Pattern.compile(regExp);
			Matcher m = p.matcher(member.getPhone());
			if (!m.matches()) {
				return JsonResultUtil.getErrorJson("请求错误！手机号码不正确！");
			}
		}
		if (member.getPw_question() == null || member.getPw_answer() == null) {
			member.setPw_question(null);
			member.setPw_answer(null);
		}

		// 学号验证
		String student_number = member.getStudent_number().toUpperCase();
		if (!student_number.startsWith("P1")) {
			return JsonResultUtil.getErrorJson("请求错误！学号填写错误！");
		}
		if (student_number.length() != 10) {
			return JsonResultUtil.getErrorJson("请求错误！学号填写错误！");
		}
		member.setStudent_number(student_number);

		// 设置年级
		char one = student_number.charAt(1);
		char second = student_number.charAt(2);
		member.setGrade("20" + one + second + "级");

		// 设置密码
		if (newpassword != null) {
			if (!newpassword.equals("")) {
				member.setPassword(StringUtil.md5(newpassword));
			}
		}

		// 上传图片
		if (pic != null) {
			if (FileUtil.isAllowUpImg(pic.getOriginalFilename())) {
				InputStream stream = null;
				try {
					stream = pic.getInputStream();
				} catch (Exception e) {
					e.printStackTrace();
				}
				IUploader uploader = UploadFacatory.getUploaer();
				String path = uploader.upload(stream, "adv",
						pic.getOriginalFilename());
				member.setPicture(path);
			} else {
				return JsonResultUtil
						.getErrorJson("不允许上传的文件格式，请上传gif,jpg,bmp,swf格式文件。");
			}
		}

		// 设置生日
		if (strBirthday != null) {
			if (!strBirthday.equals("")) {
				try {
					Date date = DateUtil.toDate(strBirthday, "yyyy-MM-dd");
					member.setBirthday(date.getTime() / 1000);
				} catch (Exception e) {
					return JsonResultUtil.getErrorJson("请求错误！生日日期错误！");
				}
			}
		}

		// 设置登录次数
		Member member2 = this.memberManager.findById(member.getMember_id());
		member.setLogincount(member2.getLogincount());

		try {
			this.memberManager.update(member);

			return JsonResultUtil.getSuccessJson("修改成功！");

		} catch (Exception e) {
			e.printStackTrace();
			return JsonResultUtil.getErrorJson("修改失败！");
		}

	}

}
